﻿using Infov1.Commands;
using System;
using System.Collections;
using System.Collections.Generic;

using System.IO;
using System.Windows;
using System.Windows.Input;
using System.Xml.Linq;
using HandyControl.Controls;
using System.Windows.Controls;



namespace Infov1.ViewModels
{
    public class SqlLinkViewModel:ViewModelBase
    {
        private string _sqlLinkStr = string.Empty;
        private readonly string configPath = "Appaction.xml";

        public string SqlLinkStr
        {
            get => _sqlLinkStr;
            set
            {
                if (_sqlLinkStr != value)
                {
                    _sqlLinkStr = value;
                    OnPropertyChanged(nameof(SqlLinkStr));
                }
            }
        }
        // 保存命令
        public ICommand SaveCommand { get; }
        //构造函数
        public SqlLinkViewModel()
        {
            LoadFromXml(); // 构造函数中加载XML数据
            SaveCommand = new RelayCommand(SaveToXml);
        }
        private void LoadFromXml()
        {
            try
            {
                if (File.Exists(configPath))
                {
                    var doc = XDocument.Load(configPath);
                    var linkValue = doc.Root?.Element("link")?.Value;
                    SqlLinkStr = linkValue ?? string.Empty;
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"读取配置文件失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void SaveToXml()
        {
            try
            {
                XDocument doc;
                if (File.Exists(configPath))
                {
                    doc = XDocument.Load(configPath);
                    var linkElement = doc.Root?.Element("link");
                    if (linkElement != null)
                    {
                        linkElement.Value = SqlLinkStr;
                    }
                    else
                    {
                        doc.Root?.Add(new XElement("link", SqlLinkStr));
                    }
                }
                else
                {
                    doc = new XDocument(
                        new XDeclaration("1.0", "utf-8", null),
                        new XElement("configuration",
                            new XElement("link", SqlLinkStr)
                        )
                    );
                }
                doc.Save(configPath);
                System.Windows.MessageBox.Show("保存成功！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"保存配置文件失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }





    }
}
